//
//  AreaChooseViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/25.
//

#import "AreaChooseViewController.h"
#import "AreaListCell.h"
#import "AreaCodeListManager.h"

@interface AreaChooseViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UITextField *searchTF;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)AreaCodeListManager *listManager;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)NSMutableArray *searchArr;
@property(nonatomic,assign)BOOL isSearch;

@end

@implementation AreaChooseViewController

-(AreaCodeListManager *)listManager{
    if(!_listManager){
        _listManager = [[AreaCodeListManager alloc]init];
        _listManager.delegate = self;
    }
    return _listManager;
}

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(NSMutableArray *)searchArr{
    if(!_searchArr){
        _searchArr = [NSMutableArray array];
    }
    return _searchArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isSearch = NO;
    [self createUI];
    [self loadData];
}

-(void)loadData{
    [self.listManager loadData];
}

-(void)createUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    [self.customNavigationBar setTitle:@"选择区号"];
    self.searchTF = [[UITextField alloc]init];
    self.searchTF.font = JPUIFontPingFangSCMedium(14);
    self.searchTF.textColor = KFontBlackColor;
    self.searchTF.backgroundColor = KbgColor;
    self.searchTF.layer.cornerRadius = 20;
    self.searchTF.layer.masksToBounds = YES;
    self.searchTF.returnKeyType = UIReturnKeySearch;
    self.searchTF.delegate = self;
    self.searchTF.tintColor = KThemeColor;
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0,0,42,40)];
    UIImageView *logoImageView = [[UIImageView alloc]initWithFrame:CGRectMake(17,12.5,15,15)];
    logoImageView.image = [UIImage imageNamed:@"area_search"];
    [leftView addSubview:logoImageView];
    self.searchTF.leftView = leftView;
    self.searchTF.leftViewMode = UITextFieldViewModeAlways;
    self.searchTF.rightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 17, 40)];
    self.searchTF.rightViewMode = UITextFieldViewModeAlways;
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:@"搜索"];
    [pStr addAttribute:NSForegroundColorAttributeName value:KFontGrayColor range:NSMakeRange(0,pStr.length)];
    [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangSCRegular(14) range:NSMakeRange(0,pStr.length)];
    self.searchTF.attributedPlaceholder = pStr;
    [self.view addSubview:self.searchTF];
    [self.searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+10);
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(@40);
    }];
    [self.searchTF addTarget:self action:@selector(textChange) forControlEvents:
      UIControlEventEditingChanged];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+58,self.currentAvailableWidth, self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-58) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 52;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.tableView registerClass:NSClassFromString(@"AreaListCell") forCellReuseIdentifier:@"AreaListCell"];
    [self.view addSubview:self.tableView];
    __weak typeof(self)self_weak_ = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self_weak_.dataArr removeAllObjects];
        [self_weak_.searchArr removeAllObjects];
        self_weak_.searchTF.text = @"";
        [self_weak_.searchTF resignFirstResponder];
        self_weak_.isSearch = NO;
        [self_weak_ loadData];
    }];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.tableView.frame = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT+58,self.currentAvailableWidth, self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-58);
            [self.tableView reloadData];
        });
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AreaListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AreaListCell"];
    AreaListModel *model = nil;
    if(_isSearch == YES){
        if(indexPath.row < self.searchArr.count){
            model = self.searchArr[indexPath.row];
        }
    }else{
        if(indexPath.row < self.dataArr.count){
            model = self.dataArr[indexPath.row];
        }
    }
    if(model){
        if([model._id isEqualToString:self.selAreaModel._id]){
            cell.isSel = YES;
        }else{
            cell.isSel = NO;
        }
        cell.model = model;
    }else{
        cell.isSel = NO;
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_isSearch == YES){
        return self.searchArr.count;
    }
    return self.dataArr.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AreaListModel *model = nil;
    if(_isSearch == YES){
        if(indexPath.row < self.searchArr.count){
            model = self.searchArr[indexPath.row];
        }
    }else{
        if(indexPath.row < self.dataArr.count){
            model = self.dataArr[indexPath.row];
        }
    }
    if(model){
        if(_selBlock){
            _selBlock(model);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 点击了搜索
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self searchData];
    return YES;
}

-(void)textChange{
    [self searchData];
}

-(void)searchData{
    [self.searchArr removeAllObjects];
    if ([self.searchTF.text isEqualToString:@""]){
        _isSearch = NO;
    }else{
        _isSearch = YES;
        NSMutableArray *nameArr = [NSMutableArray array];
        for (AreaListModel *model in self.dataArr) {
            [nameArr addObject:[NSString stringWithFormat:@"%@+%@",model.areaName,model.areaId]];
        }
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains [cd] %@",self.searchTF.text];
        NSArray *arrays =  [[NSArray alloc] initWithArray:[nameArr filteredArrayUsingPredicate:predicate]];
        for (AreaListModel *model in self.dataArr) {
                for (NSString *name in arrays) {
                    NSString *namestr = [NSString stringWithFormat:@"%@+%@",model.areaName,model.areaId];
                    if ([name isEqualToString:namestr]) {
                        [self.searchArr addObject:model];
                    }
                }
        }
    }
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.listManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [AreaListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    [self.tableView.mj_header endRefreshing];
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}

@end
